<template>
    <div class="chat-container flex flex-col h-full">
        <slot name="before-content"></slot>
        <div
            class="p-4 text-lg flex items-center text-[#519de6] w-full max-w-[1000px] mx-auto"
        >
            <img class="w-[50px] h-[50px]" :src="logo" />“岳麓CS”智能AI助教
        </div>

        <el-scrollbar
            ref="scrollbarRef"
            class="p-4 w-full max-w-[1000px] mx-auto"
        >
            <div
                v-for="(item, i) in chatHistory"
                :key="item.content"
                class="flex flex-col flex-1 chat-history"
            >
                <div
                    :class="{
                        user: item.type === 'user',
                        ai: item.type !== 'user',
                    }"
                    class="p-2 m-2"
                >
                    <pre class="whitespace-pre-wrap text-slate-900">{{
                        item.content
                    }}</pre>
                    <div
                        v-if="item.type !== 'user'"
                        @click="copyToClipboard(item.content)"
                        class="w-[fit-content] text-sm cursor-pointer text-gray-400 hover:text-gray-500"
                    >
                        复制
                    </div>
                    <slot name="after-ai-message"></slot>
                    <template
                        v-if="item.type === 'singleChoice' && item.options"
                    >
                        <div
                            v-for="o in item.options"
                            class="w-[fit-content] p-2 m-2 text-sm rounded max-w-[300px] !bg-slate-50"
                            :class="{
                                'cursor-pointer !hover:bg-slate-100':
                                    i === chatHistory.length - 1 &&
                                    !item.userAnswer,
                                '!bg-slate-200': item.userAnswer === o.id,
                            }"
                            @click="
                                i === chatHistory.length - 1 &&
                                    !item.userAnswer &&
                                    handleChoice(item.id!, o.id)
                            "
                        >
                            {{ o.id }}. {{ o.content }}
                        </div>
                    </template>
                </div>
            </div>
        </el-scrollbar>

        <!-- <div v-if="item.type === 'singleChoice'">
                    <div class="ai p-2 m-2">
                        <div class="text-sm cursor-pointer text-gray-400">
                            单选题
                        </div>
                        {{ item.content }}
   
                    </div>
                    <div
                        v-for="o in item.options"
                        class="ai p-2 m-2 cursor-pointer !hover:bg-slate-200"
                    >
                        {{ o.id }}. {{ o.content }}
                    </div>
                </div> -->
        <div class="flex flex-col w-full p-4 max-w-[600px] mx-auto">
            <div v-if="props.knowledgeBase" class="text-sm text-slate-500 p-2">
                知识库：{{ props.knowledgeBase.title
                }}<el-switch
                    size="small"
                    class="ml-1"
                    v-model="enableKnowledgeBase"
                />
            </div>

            <div class="input-container flex items-end w-full">
                <div class="w-full px-2 pb-1">
                    <el-input
                        class="w-full h-full"
                        v-model="inputVal"
                        :autosize="{ minRows: 1 }"
                        type="textarea"
                        placeholder="请输入提问内容"
                        @keydown.enter.prevent="handleSend"
                    />
                </div>
                <el-button
                    type="primary"
                    :disabled="inputVal === ''"
                    :icon="Promotion"
                    circle
                    @click="handleSend"
                />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { IContextDescriptionItem } from '@/apis/chat/interfaces'
import { Promotion } from '@element-plus/icons-vue'
import { ElButton, ElInput, ElMessage, ElScrollbar } from 'element-plus'
import { nextTick, ref } from 'vue'
import { IChatAgent, IChatMessage, chat } from '../../apis/chat'
import logo from './ailogo.png'

const props = defineProps<{
    getContextDescription?: () => IContextDescriptionItem[]
    agent?: IChatAgent
    helloMessage?: string
    knowledgeBase?: {
        id: number
        title: string
        collectionName: string
    }
}>()
const emit = defineEmits(['choice'])

const inputVal = ref('')
const enableKnowledgeBase = ref(false)
const scrollbarRef = ref<InstanceType<typeof ElScrollbar> | null>(null)

interface IMessageItem {
    id?: number
    type: 'user' | 'ai' | 'singleChoice'
    content: string
    options?: {
        id: string
        content: string
    }[]
    userAnswer?: string
    answer?: string
    [key: string]: any
}

const chatHistory = ref<IMessageItem[]>([
    // {
    //     type: 'ai',
    //     content: props.helloMessage ? props.helloMessage : '你好，我是AI小助手，有什么问题可以问我哦~',
    // },
] as any[])

const sleep = (ms: number) => {
    return new Promise((resolve) => setTimeout(resolve, ms))
}

// 插入消息
const insertMessage = async (data: IMessageItem) => {
    chatHistory.value.push({
        ...data,
        options: [],
        type: data.type,
        content: '',
    })
    const text = data.content
    for (let i = 0; i < text.length; i++) {
        const char = text.charAt(i)
        chatHistory.value[chatHistory.value.length - 1].content += char
        if (scrollbarRef.value) {
            scrollbarRef.value.scrollTo({
                top: 99999,
            })
        }
        await sleep(30)
    }

    if (data.type === 'singleChoice' && data.options) {
        chatHistory.value[chatHistory.value.length - 1].options = []
        for (let i = 0; i < data.options.length; i++) {
            const option = data.options[i]
            chatHistory.value[chatHistory.value.length - 1].options?.push({
                id: option.id,
                content: option.content,
            })
            await sleep(100)
        }
        if (scrollbarRef.value) {
            scrollbarRef.value.scrollTo({
                top: 99999,
            })
        }
    }
}

const init = async () => {
    const text = props.helloMessage
        ? props.helloMessage
        : '你好，我是“岳麓CS”智能AI助教，有什么问题可以问我哦~'

    await insertMessage({
        type: 'ai',
        content: text,
    })
}

init()

const chatHistoryToChatMessages = (): IChatMessage[] => {
    const messages: IChatMessage[] = chatHistory.value.map((item) => {
        if (item.type === 'user') {
            return {
                role: 'user',
                content: item.content,
            }
        } else if (item.type === 'ai') {
            // 从content中去掉被<think></thik>包裹的内容
            const content = item.content.replace(
                /<think>([\s\S]*?)<\/think>/g,
                ''
            )
            return {
                role: 'assistant',
                content,
            }
        } else if (item.type === 'singleChoice') {
            
            return {
                role: 'assistant',
                content: `单选题
${item.content}
${item.options?.map((o) => `${o.id}. ${o.content}`).join('\n')}

（正确答案：${item.answer}）`,
            }
        }
        return {
            role: 'assistant',
            content: item.content,
        }
    })
    const last = chatHistory.value[chatHistory.value.length - 1]
    if (last && last.type === 'singleChoice') {
        const message = messages[messages.length - 1]
        return [message]
    } else {
        return []
    }
}

// 发送
const handleSend = () => {
    const input = inputVal.value
    inputVal.value = ''
    const messages = chatHistoryToChatMessages()
    chatHistory.value.push({
        type: 'user',
        content: input,
    })
    chatHistory.value.push({
        type: 'ai',
        content: '正在思考中...',
    })
    nextTick(() => {
        if (scrollbarRef.value) {
            scrollbarRef.value.scrollTo({
                top: 99999,
            })
        }
    })
    let res = ''
    const context = props.getContextDescription
        ? props.getContextDescription()
        : []
    const chatType = props.agent || 'case'
    chat(
        {
            user: input,
            context,
            knowledgeBase: props.knowledgeBase,
            enableKnowledgeBase: enableKnowledgeBase.value,
            messages,
        },
        (str) => {
            res += str
            chatHistory.value[chatHistory.value.length - 1].content = res
            if (scrollbarRef.value) {
                scrollbarRef.value.scrollTo({
                    top: 99999,
                })
            }
        },
        chatType
    )
}

// 单选题选择
const handleChoice = (id: string | number, answer: string) => {
    // chatHistory.value.push({
    //     type: 'user',
    //     content: answer,
    // })
    
    const index = chatHistory.value.findIndex((v) => {
        return v.id === id
    })
    if (index === -1) return

    const item = chatHistory.value[index]
    chatHistory.value[index] = {
        ...item,
        userAnswer: answer,
    }
    console.log(index)

    // const answerContent = item.options?.find((o) => {
    //     return o.id === answer
    // })?.content

    // inputVal.value = `${answer}. ${answerContent}`
    inputVal.value = `${answer}`
    handleSend()

    emit('choice', id, answer)
}

const copyToClipboard = (str: string) => {
    navigator.clipboard.writeText(str)
    ElMessage.success('复制成功')
}

defineExpose({
    insertMessage,
})
</script>

<style scoped>
.chat-container {
    border-radius: 6px;
    background: linear-gradient(164deg, #f7fbff 0.46%, snow 97.43%);
}

.input-container {
    border-radius: 8px;
    padding: 12px 14px;
    opacity: 0.9;
    background: hsla(0, 0%, 100%, 0.9);
    box-shadow: 0 4px 20px 0 rgba(0, 7, 56, 0.07);
    transition: all 0.3s;
}

.input-container:hover {
    border-color: #409eff;
}

.input-container :deep(textarea) {
    border: none;
    outline: none;
    resize: none;
    font-size: 16px;
    padding: 0;
    margin: 0;
    box-shadow: none;
    overflow-y: hidden;
}

.chat-history {
    overflow-y: auto;
}

.chat-history .user,
.chat-history .ai {
    background-color: #40a0ff79;
    width: fit-content;
    /* padding: 10px;
    margin: 10px; */
    border-radius: 10px;
}

.chat-history .user {
    margin-left: auto;
}

.chat-history .ai {
    background-color: #fff;
}
</style>
